import jwt from 'jsonwebtoken'
import { asyncTasks } from '../utils/roc'
import db from '../app/database'
import { md5 } from '../utils/crypto-utils'
import { PRIVATE_KEY } from '../app/config'
import redisClient from '../app/redis'
import Api from '../utils/Api'

class LoginService extends Api {
  /**
   * 用户登录
   */
  async login(username: string, password: string, uuid: string, captcha: string) {
    if (!uuid) {
      return this.error('uuid为空!')
    }
    const redisCaptcha = await redisClient.get(uuid)
    if (!username) {
      return this.error('用户名为空!')
    } else if (!password) {
      return this.error('密码为空!')
    } else if (!captcha) {
      return this.error('验证码为空!')
    } else if (redisCaptcha !== captcha) {
      return this.error('验证码错误!', 2)
    }
    const sql = 'SELECT * FROM roc_user WHERE username = ?'
    const [err, results] = await asyncTasks(db.query(sql, [username]))
    if (err) return console.log('sql错误:', err.sqlMessage)
    const users = results[0]
    if (users.length === 0) {
      return this.error('无此用户')
    } else if (md5(password) !== users[0].password) {
      return this.error('密码错误')
    } else {
      /*
        sign(数据体, 私钥, 选项{algorithm: 算法, expiresIn: 到期时间})
        返回token
      */
      const token = jwt.sign(
        {
          id: users[0].id,
          username: users[0].username,
        },
        PRIVATE_KEY,
        {
          algorithm: 'RS256',
          expiresIn: 60 * 60 * 24,
        },
      )
      await redisClient.del(uuid)
      return this.success({ token })
    }
  }
}
export default new LoginService()
